<?php

namespace app\commission;

use app\models\pay\Pay;
use app\models\user\UserAccount;
use app\models\user\UserCommission;
use app\models\user\UserRefill;
use app\util\Debug;

/**
 * 充值
 *
 * Class Refill
 * @package app\commission
 */
class Refill
{
    /**
     * 充值策略
     *
     * 1) 最低充值金额100(后台设置)
     *
     * 2) 送对等购物券和平台券
     * 3) 送对等积分 x 12月
     *
     * 4) 积分可在积分区使用
     * 5) 平台券可以在爆品区使用
     *
     * 6) 使用平台券在爆品区(积分区), 无返佣
     */
    public function commission(Pay $pay)
    {

        $transaction = \Yii::$app->db->beginTransaction();

        try {

            // refill
            $refill = UserRefill::findOne(['sn' => $pay->sn]);
            if (!$refill) {
                throw new \Exception('充值返佣失败:' . json_encode($pay));
            }
            $refill->status = 1;
            $refill->save();

            // account
            $account = UserAccount::findOne(['user_id' => $refill->user_id]);
            $account->ticket += $refill->amount;
            $account->platform_ticket += $refill->amount;
            $account->score += $refill->amount;
            $account->save();

            // commission
            $commission = new UserCommission();
            $commission->user_id = $refill->user_id;
            $commission->fans_id = $refill->user_id;
            $commission->ticket = $refill->amount;
            $commission->platform_ticket = $refill->amount;
            $commission->score = $refill->amount;
            $commission->refill_id = $refill->id;
            $commission->award_name = '充值';
            $commission->award_type = 2;
            $commission->status = 1;
            $commission->save();

            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            Debug::commission('refill-fail', $e->getMessage());
        }
    }
}